package com.lastproject.web.bean;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;

import com.lastproject.dto.CategoryDTO;
import com.lastproject.ejb.dao.CategoryDAORemote;
import com.lastproject.ejb.dao.CheckPermissionDAORemote;

public class CategoryBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7241631623931709819L;

	@EJB
	CategoryDAORemote categoryDAORemote;

	CategoryDTO categoryDTO;

	boolean alreadyCreated = false;

	public CategoryBean() {

	}
	
	@EJB
	CheckPermissionDAORemote checkPermissionDAORemote;
	
	public void preRenderView(ComponentSystemEvent event) {
        if (!checkPermissionDAORemote.hasSurveyManagementRights(true)){
        	FacesContext fc = FacesContext.getCurrentInstance();
        	ExternalContext ec = fc.getExternalContext();
        	try {
				ec.redirect("restrictedAccess.xhtml");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
    }

	/**
	 * Create a category
	 * 
	 * @return Returns a String containing [nextPage].xhtml
	 */
	public String createCategory() {
		alreadyCreated = false;
		List<CategoryDTO> catList = new ArrayList<CategoryDTO>();
		catList = categoryDAORemote.findAll();

		for (CategoryDTO c : catList) {
			if (c.getName().equals(categoryDTO.getName())) {
				System.out.println("lofasz: " + c.getName());
				alreadyCreated = true;
			}
		}

		if (alreadyCreated == false) {
			categoryDAORemote.create(categoryDTO);

			categoryDTO.setName("");
			return "createTopic.xhtml";
		}

		return "createCategory.xhtml";
	}

	public String back() {
		categoryDTO.setName("");
		alreadyCreated = false;
		return "createTopic.xhtml";
	}

	public CategoryDTO getCategoryDTO() {
		return categoryDTO;
	}

	public void setCategoryDTO(CategoryDTO categoryDTO) {
		this.categoryDTO = categoryDTO;
	}

	public boolean isAlreadyCreated() {
		return alreadyCreated;
	}

	public void setAlreadyCreated(boolean alreadyCreated) {
		this.alreadyCreated = alreadyCreated;
	}

}
